<?php

namespace services\models;

use Yii;
use yii\db\Query;
/**
 * This is the model class for table "product".
 *
 * @property string $product_id
 * @property integer $goods_id
 * @property integer $type
 * @property integer $sale_status
 * @property double $sale_price
 * @property string $try_price
 */
class Product extends \common\models\Product
{
    public static $TYPE_DESC = [1 => '试用', 2 => '购买'];
    public static $_TYPE_TRY = 1;
    public static $_TYPE_SALE = 2;

    public static $SALE_STATUS_DESC = ['下架', '上架'];
    public static $_SALE_STATUS_OFF_SHELF = 0;
    public static $_SALE_STATUS_ON_SHELF = 1;


    public static $_PRICE_TYPE_RMB = 0;
    public static $_PRICE_TYPE_TRY = 1;

    public static function getDb()
    {
        return \Yii::$app->db;
    }


    public function getDetail()
    {
        return $this->hasOne(ProductDetail::className(), ['product_id' => 'product_id']);
    }

    public function getStock()
    {
        return $this->hasOne(ProductStock::className(), ['product_id' => 'product_id']);
    }

    public function getGoods()
    {
        return $this->hasOne(Goods::className(), ['goods_id' => 'goods_id']);
    }

    /**
     * get product name from cache
     * @param $product_id
     * @return string
     */
    public static function getNameFromCache($product_id)
    {
        #todo
        return Yii::$app->redis->hget('todo' . $product_id, 'product_name');

    }

    /**
     * 通过SKU ID获取信息
     * @param int $product_id SKU ID
     * @param $to_array 是否转换数组
     * @return array SKU信息
     * @return 
     */
    public static function findByProductId($product_id,$to_array=true,$sale_status = true) {

        $var = self::find()->where('product_id=:product_id AND status=:status', [':product_id' => $product_id, ':status' => 0]);
        if($sale_status) {
            $var = $var->andWhere(['sale_status'=>1]);
        }
        $var = $var->one();
        
        if(!$var && $to_array) {
           return [];
        }
        
        if($to_array) {
            return \yii\helpers\ArrayHelper::toArray($var);
        }
        return $var;
    }

    public static function findByGoodsIdAll($goods_id) {
        $vars = self::find()->where('goods_id=:goods_id AND status=:status AND sale_status = 1', [':goods_id' => $goods_id, ':status' => 0])->all();
        if(empty($vars)) {
            return [];
        }

        return \yii\helpers\ArrayHelper::toArray($vars);
    }

    /**
     * 通过商品ID，获取制定商品下的所有SKU信息
     * @param int $goods_id 商品ID
     * @return array
     */
    public static function findByGoodsIdFromDb($goods_id) {
        $vars = self::find()->where('goods_id=:goods_id AND status=0', [':goods_id' => $goods_id])->all();
        if(empty($vars)) {
            return [];
        }

        return \yii\helpers\ArrayHelper::toArray($vars);
    }
    
    /**
     * 验证免费申领注册时间限制，只针对免费试用，
     * @param int|MemberInfo $member liektry的member_no 或者 Member
     */
    public function checkRegisterLimt($member)
    {

       $goodsExtInfo = GoodsExt::findByGoodsId($this->goods_id,['buy_limit']);
        if(!empty($goodsExtInfo['buy_limit']))
        {
           $buy_limit  = unserialize($goodsExtInfo['buy_limit']);

            if(isset($buy_limit['register_limit']) && !empty($buy_limit['register_limit']))
            {
                if(!empty($member))
                {
                    //获取用户信息
                    if($member instanceof MemberInfo){
                        $memberinfo = &$member;
                    }
                    
                    if(is_integer($member)){
                        $memberinfo = MemberInfo::cache($member);
                    }
                    $member_register_time = $memberinfo->add_time;
                    
                    $member_register_time = strtotime($member_register_time);
                    //$member_register_time = '1957539200';
                    $register_limit_starttime = strtotime($buy_limit['register_limit_startdate'].' '.$buy_limit['register_limit_starthour'].':'.$buy_limit['register_limit_startminute']);
                    $register_limit_endtime = strtotime($buy_limit['register_limit_enddate'].' '.$buy_limit['register_limit_endhour'].':'.$buy_limit['register_limit_endminute']);
            
                    if(($register_limit_starttime <= time() && $register_limit_endtime > time())
                        || (empty($buy_limit['register_limit_enddate']) && $register_limit_starttime <= time())
                        || (empty($buy_limit['register_limit_startdate']) && $register_limit_endtime > time()))
                    {
                        $goods_info =  GoodsDetail::findByGoodsId($this->goods_id,['goods_name']);
                        if(!empty($buy_limit['register_startdate']) && !empty($buy_limit['register_enddate']))
                        {
                            if($member_register_time < strtotime($buy_limit['register_startdate']) || $member_register_time > strtotime($buy_limit['register_enddate'].' 23:59:59'))
                            {
                                $this->addError($this->goods_id,  $goods_info['goods_name'].'，限'.$buy_limit['register_startdate'].'到'.$buy_limit['register_enddate'].'之间注册的用户试用申领');
                                 return false;
                            }
                        }elseif(!empty($buy_limit['register_startdate']) && empty($buy_limit['register_enddate']))
                        {
                            if($member_register_time < strtotime($buy_limit['register_startdate']))
                            {
                                $this->addError($this->goods_id, $goods_info['goods_name'].'，限'.$buy_limit['register_startdate'].'之后注册的用户试用申领');
                                return false;
                            }
                        }elseif(empty($buy_limit['register_startdate']) && !empty($buy_limit['register_enddate']) )
                        {
                            if($member_register_time > strtotime($buy_limit['register_enddate'].' 23:59:59'))
                            {
                                $this->addError($this->goods_id, $goods_info['goods_name'].'，限'.$buy_limit['register_enddate'].'之前注册的用户试用申领');
                                return false;
                            }
                        }
                    }
                 }
              }
        }
        return true;
    }
    
    /**
     * 根据货品ID查询产品相关信息，仅后台试用 by fengsiliang
     * @param int $product_id 货品ID
     */
    public static function getGoodsInfo()
    {
        $query = new Query(); 
        return $query->select(['p.product_id', 'gt.goods_id', 'gt.goods_name'])  
                     ->from('d_try.goods_detail gt')
                     ->leftJoin('d_try.product p', 'gt.goods_id=p.goods_id')
                     ->all();  
         
    }
    
    /**
     * 通过goods_id获取商品默认product_id
     */
    public static function findByGoodsIdDefault($goods_id) {
        $var = self::find()->where('goods_id=:goods_id AND status=:status AND sale_status = 1 AND default_sku = 1', [':goods_id' => $goods_id, ':status' => 0])
                           ->one();
        return \yii\helpers\ArrayHelper::toArray($var);
    }
}
